<template>
  <div class="analyise-search-body">
    <slot name="timeBar">
    </slot>
    <Treeselect noChildrenText="没有更多数据" noOptionsText="暂无数据" :loadOptions="loadOptions" v-model="filterText" :options="treeData" :alwaysOpen="true" :max-height="450" placeholder="请选择设备..." @select="onSelect" />
    <div class="drawer-footer" v-if="!hideExport">
      <Button type="primary" @click="handleExport">导出</Button>
    </div>
  </div>
</template>
<script>
import { getGroupList, getDeviceListOfNew } from "@/api"
export default {
  props: {
    companyId: {
      type: String
    },
    hideExport: {
      type: Boolean,
      default: false
    }
  },
  data: () => ({
    filterText: null,
    options: {},
    treeData: [],
    dateType: ""
  }),
  watch: {
    companyId() {
      this.fetchGetGroupList()
    }
  },
  mounted() {
    this.fetchGetGroupList()
  },
  beforeDestroy() {},
  methods: {
    fetchGetGroupList() {
      const vm = this
      const companyId = vm.companyId
      if (!companyId) {
        return
      }
      const params = {
        companyId
      }
      getGroupList(params).then(res => {
        if (res.data.list.length === 0) {
          this.treeData = []
          return
        }

        const treeData = res.data.list.map(t => ({
          label: t.name,
          ...t,
          children: null
        }))
        this.filterText = treeData[0].id
        this.$emit("change", {
          groupId: treeData[0].id,
          deviceNo: null
        })
        this.treeData = treeData
      })
    },

    loadOptions({ action, parentNode, callback }) {
      const vm = this
      if (action === "LOAD_CHILDREN_OPTIONS") {
        const params = {
          groupId: parentNode.id,
          companyId: vm.companyId,
          size: 1000,
          filter:true
        }
        getDeviceListOfNew(params).then(res => {
          const { list } = res.data
          if (list.length === 0) {
            parentNode.children = []
            callback()
          }
          parentNode.children = list.map(t => ({
            label: t.name,
            ...t
          }))
          callback()
        })
      }
    },

    onSelect(value) {
      const vm = this
      // 区域
      if (value.children) {
        this.$emit("change", {
          groupId: value.id,
          deviceNo: null
        })
      } else {
        // 设备
        this.$emit("change", {
          groupId: null,
          deviceNo: value.deviceId
        })
      }
    },

    handleExport() {
      this.$emit("download")
    }
  }
}
</script>
